import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { constantRoutes, anyRoutes } from '@/router';
import loginApi from "@/api/login";
import Layout from '@/layout'

function loadView(x) {
  let view = "";
  if (x.src == null || x.src == "") {
    return Layout;
  } else {
    view = x.src;
  }

  // if (process.env.NODE_ENV === 'development') {
  return resolve => require([`@/views/${view}.vue`], resolve)
  // } else {
  //   // 使用 import 实现生产环境的路由懒加载
  //   return () => import(`@/views/${view}.vue`)
  // }
}

function getRouter(tree) {
  let temp = [];
  tree.map(x => {
    let stemp = {};
    stemp.meta = {};
    stemp.name = x.name;
    stemp.path = x.path;
    stemp.component = loadView(x);
    stemp.meta.roles = [x.id.toString()];
    stemp.meta.title = x.name;
    stemp.meta.icon = x.icon;
    if (x.children) {
      stemp.children = getRouter(x.children);
    }
    temp.push(stemp);
  });
  return temp;
}

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    resultAsyncRoutes: [],
    resultAllRoutes: [],
    info:{}
  }
}

const state = getDefaultState()

const mutations = {
  SET_INFO: (state, info) => {
    state.info = info
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_RESULTASYNCROUTES: (state, asyncRoutes) => {

    //vuex保存当前用户的异步路由，注意，一个用户需要展示完成路由：常量、异步、任意路由
    state.resultAsyncRoutes = asyncRoutes;
    //计算出当前用户需要展示所有路由
    // 直接将所有的路由丢到addRoutes，会出现警告，因为有些路由重复了，比如常量路由中的首页、登录页，我们在一开始就加入了，不应该再加入
    // 所以就会有警告提示，你重复添加路由了 [vue-router] Duplicate named routes definition: { name: "Dashboard", path: "/dashboard" }
    state.resultAllRoutes = constantRoutes.concat(state.resultAsyncRoutes);
    // 只需将异步路由和任意路由添加就可以了
    state.resultAllRoutes = state.resultAsyncRoutes.concat(anyRoutes);
    //给路由器添加新的路由
    // router.addRoutes 是在已有的路由上，再添加路由
    router.addRoutes(state.resultAllRoutes)
    // 注意：router.addRoutes动态添加路由后并不会修改router.options.routes，Vue这么设计的
    // 如果修获取获取最新的options.routes，需要手动修改 router.options.routes = state.resultAllRputes
    router.options.routes = state.resultAllRoutes
  }

}

import { getImg } from "@/api/help_func/index";

const actions = {
  async login({ commit }, userInfo) {
    let res = await loginApi.doLogin(userInfo);
    if (res.code == 0) {
      const data = {
        'token': res.data.token
      }
      setToken(data.token)// 将token存储在cookie中
      commit('SET_TOKEN', data.token)


      //  router.push('/roles')
    }

  },

  async getInfo({ commit }) {
    let res = await loginApi.getUserInfo();
    commit('SET_INFO', res.data)
    
    let user = res.data;
    let roles = res.data.roles.split(",");
    let avatar = getImg(user.avatar);
    const data = {
      'roles': roles,
      'name': user.name,
      'avatar': avatar
    }
    // commit('SET_ROLES', data.roles)
    commit('SET_NAME', data.name)
    commit('SET_AVATAR', avatar)
    let drouter = [];
    let res1 = await loginApi.getUserRouter()
    if (res1.code === 0) {
      let data = res1.data;
      drouter = getRouter(data);
      commit('SET_RESULTASYNCROUTES', drouter);
    }
  },

  // 登出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      // commit('SET_ROLES', [])
      commit('SET_NAME', "")
      removeToken()
      resolve()
    })
  },


  // user login
  // login({ commit }, userInfo) {
  //   const { username, password } = userInfo
  //   return new Promise((resolve, reject) => {
  //     login({ username: username.trim(), password: password }).then(response => {
  //       const { data } = response
  //       commit('SET_TOKEN', data.token)
  //       setToken(data.token)
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         return reject('Verification failed, please Login again.')
  //       }

  //       const { name, avatar } = data

  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // // user logout
  // logout({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token).then(() => {
  //       removeToken() // must remove  token  first
  //       resetRouter()
  //       commit('RESET_STATE')
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

